// abnormallyReport.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    faultItems: [
      { name: '乱贴广告', value: '乱贴广告' },
      { name: '路灯不亮', value: '路灯不亮'},
      { name: '路灯闪烁', value: '路灯闪烁' },
      { name: '灯杆破损', value: '灯杆破损' },
      { name: '贴牌损坏', value: '贴牌损坏' },
      { name: '其他故障', value: '其他故障' }
    ],
    faultDescription: [],
    facilitiesNo: '',//设施编号
    streetLampType: '',//路灯类型
    address: '',//地址
    jwdInfo: '',//经纬度
    powerUnit: '',//权属单位
    name: '',
    phone: '',
    deptid: 0,//部门id
    loading: false,
    userInfo: {},
    exlist: [],
    radioVal: '',
    exobj: {},
    moreChflag: true,
    id: '',
    type: 0,
    tittleInfo:'',
    mapshow:true,
    longitude: 113.324520,
    latitude: 23.099994,
    remark:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    // options 中的 scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
    var scene = decodeURIComponent(options.scene);
    if (scene != 'undefined' || !scene){
      that.setData({ id: scene });
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    var scene = that.data.id;
    if (scene != '') {
      //查询异常信息
      that.searchEX(scene);
    } else {
      //需要登录系统账号信息
      that.checkLogin();
    }
    console.log("调用onshow")
  },
  checkLogin: function () {
    var name = wx.getStorageSync('userName')
    if (name == '' || name == null) {
      wx.showModal({
        title: '提示',
        content: "用户未登录",
        confirmText: '去登录',
        showCancel: false,
        success: function () {
          wx.navigateTo({
            url: '../login/login',
          })
        }
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },
  //当获取焦点时触发
  focusFun: function(e){
    var that = this;
    var param = e.target.dataset.param;
    that.searchEXlist();
    var val = 0;
    var tittle = '终端编号选择';
    if (param==1){
      val = 1;
      tittle = '终端编号选择';
    } else if (param == 3){
      val = 3;
      tittle = '地址选择';
    } else if (param == 4) {
      val = 4;
      tittle = '经纬度选择';
    }
    that.setData({type:val,tittleInfo:tittle});
  },
  //根据id查询
  searchEX: function(id){
    var that = this;
    var header = { 'content-type': 'application/x-www-form-urlencoded' };
    var param = {id: id};
    wx.request({
      url: app.url + '/web/exceptionReport/getById.htm',
      data: app.ecbEncrypto(param),
      method: 'POST',
      header: header,
      success: function (res) {
        var decodingStr = app.ecbDecrypto(res.data)
        var rest = JSON.parse(decodingStr)
        console.log(rest);
        if (rest.isSuccess == 0) {
          var entity = rest.result;
          that.setData({
            facilitiesNo: entity.meterAddr,//设施编号
            streetLampType: entity.streetLampType,//路灯类型
            address: entity.address,//地址
            jwdInfo: entity.lngLat,//经纬度
            powerUnit: entity.powerUnit,//权属单位
            deptid: entity.deptid
          });
        }
      }
    })
  },
  //查询集合获取终端编号
  searchEXlist: function () {
    var that = this;
    var header = { 'content-type': 'application/x-www-form-urlencoded' };
    wx.request({
      url: app.url + '/web/exceptionReport/select.htm',
      data: {},
      method: 'POST',
      header: header,
      success: function (res) {
        var decodingStr = app.ecbDecrypto(res.data)
        var rest = JSON.parse(decodingStr)
        console.log(rest);
        if (rest.isSuccess == 0) {
          that.setData({
            exlist: rest.result,
            moreChflag: false
          });
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      faultItems: [
        { name: '乱贴广告', value: '乱贴广告' },
        { name: '路灯不亮', value: '路灯不亮' },
        { name: '路灯闪烁', value: '路灯闪烁' },
        { name: '灯杆破损', value: '灯杆破损' },
        { name: '贴牌损坏', value: '贴牌损坏' },
        { name: '其他故障', value: '其他故障' }
      ],
      faultDescription: [],
      facilitiesNo: '',//设施编号
      streetLampType: '',//路灯类型
      address: '',//地址
      jwdInfo: '',//经纬度
      powerUnit: '',//权属单位
      name: '',
      phone: '',
      deptid: 0,//部门id
      loading: false,
      userInfo: {},
      exlist: [],
      radioVal: '',
      exobj: {},
      moreChflag: true,
      id: '',
      type: 0,
      tittleInfo: '',
      mapshow: true,
      longitude: 113.324520,
      latitude: 23.099994,
      remark: '', showLoading: true })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  //为空判断
  getValue:function(e){
    var that = this;
    var param = e.target.dataset.param;
    var val = e.detail.value;
    if(param == 1){
      that.setData({ facilitiesNo: val.trim()});
    }else if(param == 2){
      that.setData({ streetLampType: val.trim() });
    }else if(param == 3){
      that.setData({ address: val.trim() });
    } else if (param == 4){
      that.setData({ jwdInfo: val.trim() });
    } else if (param == 5){
      that.setData({ powerUnit: val.trim() });
    } else if (param == 6) {
      that.setData({ name: val.trim() });
    } else if (param == 7) {
      that.setData({ phone: val.trim() });
    } else if (param == 8) {
      that.setData({ remark: val.trim() });
    }
  },
  checkboxChange:function(e){
    var cboxs = e.detail.value;
    var val = '';
    for(var i in cboxs){
      if(cboxs.length-1 == i){
        val += cboxs[i]
      }else{
        val += cboxs[i] + ','
      }
    }
    this.setData({ faultDescription:val});
  },
  exsubmit: function(){
    var that = this;
    var faultDescription = that.data.faultDescription;
    var facilitiesNo = that.data.facilitiesNo;
    var streetLampType = that.data.streetLampType;
    var address = that.data.address;
    var jwdInfo = that.data.jwdInfo;
    var powerUnit = that.data.powerUnit;
    var name = that.data.name;
    var phone = that.data.phone;
    var remark = that.data.remark;
    if (facilitiesNo == '') {
      wx.showToast({
        title: '设施编号不能为空',
        image: '../../images/error.png',
        duration: 2000,
        mask: true
      })
      return false;
    }
    if (streetLampType == '') {
      wx.showToast({
        title: '路灯类型不能为空',
        image: '../../images/error.png',
        duration: 2000,
        mask: true
      })
      return false;
    }
    if (address == '') {
      wx.showToast({
        title: '地址不能为空',
        image: '../../images/error.png',
        duration: 2000,
        mask: true
      })
      return false;
    }
    if (jwdInfo == '') {
      wx.showToast({
        title: '经纬度不能为空',
        image: '../../images/error.png',
        duration: 2000,
        mask: true
      })
      return false;
    }
    if (powerUnit == '') {
      wx.showToast({
        title: '单位不能为空',
        image: '../../images/error.png',
        duration: 2000,
        mask: true
      })
      return false;
    }
    if (faultDescription.length==0) {
      wx.showToast({
        title: '故障描述至少选一项',
        image: '../../images/error.png',
        duration: 2000,
        mask: true
      })
      return false;
    }
    // if (name == '') {
    //   wx.showToast({
    //     title: '名字不能为空',
    //     image: '../../images/error.png',
    //     duration: 2000,
    //     mask: true
    //   })
    //   return false;
    // }
    var preg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
    var greg = /^(0\d{2,3}-\d{7,8})$/;
    // if (phone == '') {
    //   wx.showToast({
    //     title: '电话不能为空',
    //     image: '../../images/error.png',
    //     duration: 2000,
    //     mask: true
    //   })
    //   return false;
    // } 
    if((!preg.test(phone) || phone.length!=11) && !greg.test(phone) && phone != ''){
      wx.showToast({
        title: '电话格式不正确',
        image: '../../images/error.png',
        duration: 2000,
        mask: true
      })
      return false;
    }
    var params= {
      faultDescription:faultDescription,
      facilitiesNo:facilitiesNo,
      streetLampType:streetLampType,
      address:address,
      jwdInfo:jwdInfo,
      powerUnit:powerUnit,
      name:name,
      phone:phone,
      deptid: that.data.deptid,
      remark: remark,
      imgUrl: that.data.imgUrl,
    }
    that.setData({loading:true});
    var header = { 'content-type': 'application/x-www-form-urlencoded' }
    var encodingStr = app.ecbEncrypto(params)
    wx.request({
      url: app.url + '/web/exceptionReport/add.htm',
      data: encodingStr,
      method: 'POST',
      type: 'json',
      success: function(res){
        var decodingStr = app.ecbDecrypto(res.data);
        var rest = JSON.parse(decodingStr);
        that.setData({ loading: false });
        if (rest.isSuccess == 0) {
          wx.showToast({
            title: '成功',
            icon: 'success',
            duration: 2000,
            success: function () {
              setTimeout(function () {
                //要延时执行的代码
                wx.switchTab({
                  url: '../index/index',
                })
                that.setData({
                  faultItems: [
                    { name: '乱贴广告', value: '乱贴广告' },
                    { name: '路灯不亮', value: '路灯不亮' },
                    { name: '路灯闪烁', value: '路灯闪烁' },
                    { name: '灯杆破损', value: '灯杆破损' },
                    { name: '贴牌损坏', value: '贴牌损坏' },
                    { name: '其他故障', value: '其他故障' }
                  ],
                  faultDescription: [],
                  facilitiesNo: '',//设施编号
                  streetLampType: '',//路灯类型
                  address: '',//地址
                  jwdInfo: '',//经纬度
                  powerUnit: '',//权属单位
                  name: '',
                  phone: '',
                  deptid: 0,//部门id
                  loading: false,
                  userInfo: {},
                  exlist: [],
                  radioVal: '',
                  exobj: {},
                  moreChflag: true,
                  id: '',
                  type: 0,
                  tittleInfo: '',
                  mapshow: true,
                  longitude: 113.324520,
                  latitude: 23.099994,
                  remark: ''})
              }, 2000) //延迟时间
            }
          })
        }else{
          wx.showToast({
            title: '异常上报失败',
            image: '../../images/error.png',
            duration: 2000
          })
        }
      }
    })
  },
  clickFun: function(e){
    var id = e.currentTarget.dataset.id;
    var ob = e.currentTarget.dataset.ob;
    this.setData({ radioVal: id ,exobj: ob});
  },
  sureButton: function () {
    var that = this;
    that.setData({ 
      moreChflag: true, 
      facilitiesNo: that.data.exobj.meterAddr,
      address: that.data.exobj.address,
      jwdInfo: that.data.exobj.lngLat,
      deptid: that.data.exobj.deptid,
      streetLampType: that.data.exobj.streetLampType,//路灯类型
      powerUnit: that.data.exobj.powerUnit//权属单位
    });
  },
  hideMoreCh: function () {
    this.setData({ moreChflag: true })
  },
  mapshow: function(){
    this.setData({ mapshow: !this.data.mapshow })
  },
  openMap: function (event) {
    var that=this
    if (this.data.jwdInfo!=""){
      that.setData({
        longitude: parseFloat(this.data.jwdInfo.split(',')[0]),
        latitude: parseFloat(this.data.jwdInfo.split(',')[1])
      })
      wx.openLocation({
        latitude: that.data.latitude,
        longitude: that.data.longitude,
        scale: 28
      })
    }else{
      wx.getLocation({
        success: function (res) {
          console.log('0000')
          that.setData({
            longitude: res.longitude,
            latitude: res.latitude
          })
          wx.openLocation({
            latitude: that.data.latitude,
            longitude: that.data.longitude,
            scale: 28
          })
        }
      })
    }    
  },
  chooseImage(e) {
    var that = this;
    var header = {
      'content-type': 'application/x-www-form-urlencoded',
      'Accept-Encoding': 'gzip, deflate',
      'Accept-Language': 'zh-CN,zh; q=0.8',
      'Accept': '*/*',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive',
      'Content-Length': '64',
      'Pragma': 'no-cache',
    };
    wx.chooseImage({
      success(res) {
        const tempFilePaths = res.tempFilePaths

        console.log(tempFilePaths[0]);

        wx.uploadFile({
          url: app.url + '/api/account/wxupload.htm',

          filePath: tempFilePaths[0],
          name: 'file',
          formData: {
            'user': 'test'
          },
          success(res) {
            console.log(res.data)
            that.setData({
              imgUrl: res.data,
            })
            that.setData({
              imgshow: tempFilePaths[0],
            })
          }
        })

      }
    })
  },
})